package com.tianyu.sports.controller;

import com.tianyu.sports.bean.Result;
import com.tianyu.sports.utils.HttpUtil;
import com.tianyu.sports.utils.ResultUtil;
import com.tianyu.sports.utils.WxPublicPay;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author ljj
 * @data 2018/6/12
 */

@RestController
@RequestMapping(value = "/wx")
public class WxController {

    private static final Logger logger = LoggerFactory.getLogger(WxController.class);

    /**
     * 微信授权
     */
    @RequestMapping(value = "/getOpenid",method = RequestMethod.GET)
    public void getOpenid(){
        try {
            String params = "appid=" + WxPublicPay.appid
                    +"&redirect_uri="+URLEncoder.encode(WxPublicPay.redirect_uri,"GBK")
                    +"&response_type="+ WxPublicPay.response_type
                    +"&scope="+ WxPublicPay.scope
                    +"&state="+ WxPublicPay.state+"#wechat_redirect";
                    HttpUtil.get(WxPublicPay.authorize_url,params);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }
    /**
     * 获取用户详细信息
     * @param code
     * @return
     */
    @RequestMapping(value = "/getUserInfo")
    public Result getUserInfo(String code){
        //1.先拿code获取网页授权access_token以及openid
        String params = "appid=" + WxPublicPay.appid + "&secret=" + WxPublicPay.secret + "&code=" + code +"&grant_type=" + WxPublicPay.grant_type;
        String  openid =HttpUtil.get(WxPublicPay.access_token_url,params);
        //2.刷新access_token
        JSONObject jsonObject=JSONObject.fromObject(openid);
        String params1 = "appid=" + WxPublicPay.appid + "&grant_type=" + "refresh_token" + "&refresh_token=" + "" +jsonObject.get("refresh_token");
        String  access_token =HttpUtil.get(WxPublicPay.refresh_token_url,params1);
        //3.用拿到的access_token和openid获取unionID
        JSONObject jsonObject1=JSONObject.fromObject(access_token);
        String params2 = "access_token=" + jsonObject1.get("access_token") + "&openid=" + jsonObject1.get("openid")+ "&lang=" + "zh_CN";
        String  unionID =HttpUtil.get(WxPublicPay.userinfo_url,params2);
        return ResultUtil.success(unionID);
    }
}
